$(function(){
	$('#customer-table').bootstrapTable({
		method : 'post',
		url : 'system/customer/getList',
		cache : false,
		contentType: "application/json",//远程数据请求的“contentType”类型（如：application/json，application/x-www-form-urlencoded）。默认值application/json。
		height : $(window).height()-180,
		undefinedText : "--",//定义默认的undefined显示文字。
		striped : true,//使表格带有条纹。
		sortName : "createTime",
		sortOrder : "desc",
		dataType : "json",
		pagination : true,//设置True在表格底部显示分页工具栏。
		sidePagination : "server", //定义表格分页的位置，只能是“client”（客户端）和“server”（服务器端）。
		pageSize : 25,
		pageList : [ 10, 25, 50, 100, 200 ],
		search : true,//启用搜索输入框。
		showColumns : true,//设置为True可显示表格显示/隐藏列表。
		showToggle:true,//设置为True可显示切换普通表格和名片（card）布局。
		showRefresh : true,//设置为True可显示刷新按钮。
		minimumCountColumns : 2,//表格显示/隐藏列表时可设置最小隐藏的列数。
		clickToSelect : true,//设置为True时点击行即可选中单选/复选框。
		toolbar : "#toolbar",//自定义工具栏
		queryParamsType : "limit",//设置为“limit”可以发送标准的RESTFul类型的参数请求。
		queryParams : function(params) {
			return {
				limit : params.limit,
				offset : params.offset,
				sort : params.sort,
				order : params.order,
				or : true,
				customerPhone : params.search,
				customerAccount : params.search,
				customerName : params.search,
				customerGender : params.search,
				customerCompany : params.search,
				deviceSystem : params.search,
				deviceVendor : params.search,
				deviceModel : params.search,
				lastLoginAddress : params.search
			};
		},
		responseHandler : function(response){
			if(response.result && response.itemCount){
				return {
					"rows": response.result,
					"total": response.itemCount
				};
			}else{
				return {
					"rows": [],
					"total": 0
				};
			}
		},
		columns : [ {
			field : 'state',
			checkbox : true
		}, {
			field : 'customerPhone',
			title : '手机号',
			align : 'center',
			valign : 'middle',
			sortable : true
		}, {
			field : 'customerName',
			title : '姓名',
			align : 'center',
			valign : 'middle',
			sortable : true,
			formatter: nameFormatter
		}, {
			field : 'customerGender',
			title : '性别',
			align : 'center',
			valign : 'middle',
			sortable : true,
			formatter: genderFormatter
		}, {
			field : 'customerCompany',
			title : '单位',
			align : 'center',
			valign : 'middle',
			sortable : true
		}, {
			field : 'customerPhoto',
			title : '头像',
			align : 'center',
			valign : 'middle',
            sortable : true,
            formatter: iconFormatter
		}, {
			field : 'deviceSystem',
			title : '手机系统',
			align : 'center',
			valign : 'middle',
            sortable : true
		}, {
			field : 'lastLoginAddress',
			title : '最近登录地点',
			align : 'center',
			valign : 'middle',
            sortable : true
		}, {
			field : 'lastLoginTime',
			title : '最近登录时间',
			align : 'center',
			valign : 'middle',
            sortable : true
		}, {
			field : 'createTime',
			title : '创建时间',
			align : 'center',
			valign : 'middle',
            sortable : true
		}, {
			field : 'locked',
			title : '锁定状态',
			align : 'center',
			valign : 'middle',
            sortable : true,
            formatter: lockedFormatter
		}, {
			field : 'operate',
			title : '操作',
			align : 'center',
			valign : 'middle',
			clickToSelect : false,
			formatter : operateFormatter,
			events : operateEvents
		} ]
	});
	
	$("#addCustomer-btn").click(function(){
		$('#customerId').val("");
		$("#customerPhone").val("");
		$("#customerPhone").removeAttr('readonly');
		$("#customerName").val("");
		$("input[name='customerGender']").removeAttr('checked');
		$("#customerCompany").val("");
		$(".info-label").html("");
		$("#customerinfo-modal").modal("show");
	});
	
	$("#delCustomer-btn").click(function(){
		var array = $('#customer-table').bootstrapTable("getSelections");
		if(array!=null && array.length>0){
			var ids = "";
			$.each(array,function(i,v){
				ids+=v.customerId+",";
			});
			bootbox.confirm("您确定要将客户删除吗？", function(result){
				if(result){
					del("system/customer/delCustomers/"+ids,function (json, textStatus) {
						if(json.success){
							bootbox.alert("客户删除成功");
							$('#customer-table').bootstrapTable("refresh",{silent: true});
						}else{
							bootbox.alert("客户删除失败");
						}
					});
				}
			});
		}else{
			bootbox.alert("请选择要删除的客户");
		}
	});
	
	$("#resetPassword-btn").click(function(){
		var array = $('#customer-table').bootstrapTable("getSelections");
		if(array!=null && array.length>0){
			var ids = "";
			$.each(array,function(i,v){
				ids+=v.customerId+",";
			});
			bootbox.confirm("您确定要恢复初始密码吗？", function(result){
				if(result){
					post("system/customer/resetCustomerPassword",function (json, textStatus) {
						if(json.success){
							bootbox.alert("密码重置成功");
						}else{
							bootbox.alert("密码重置失败");
						}
					},{ids:ids});
				}
			});
		}else{
			bootbox.alert("请选择要重置密码的用户");
		}
	});
	
	$("#locked-btn").click(function(){
		var array = $('#customer-table').bootstrapTable("getSelections");
		if(array!=null && array.length>0){
			var ids = "";
			$.each(array,function(i,v){
				ids+=v.customerId+",";
			});
			bootbox.confirm("您确定要锁定/解锁用户吗？", function(result){
				if(result){
					post("system/customer/lockedCustomer",function (json, textStatus) {
						if(json.success){
							bootbox.alert("锁定/解锁用户成功");
							$('#customer-table').bootstrapTable("refresh",{silent: true});
						}else{
							bootbox.alert("锁定/解锁用户失败");
						}
					},{ids:ids});
				}
			});
		}else{
			bootbox.alert("请选择要重置密码的用户");
		}
	});
	
	$("#customerinfo-save-btn").click(function(){
		var customerId = $('#customerId').val();
		var customerPhone = $("#customerPhone").val();
		var customerName = $("#customerName").val();
		var customerGender = $("input[name='customerGender']:checked").val();
		var customerCompany = $("#customerCompany").val();
		if(isEmpty(customerPhone)){
			$("#customerPhone-label").html("<code>*请输入客户手机号*</code>");
			return false;
		}
		customerPhone = customerPhone.replace(/(^\s*)|(\s*$)/g, "");
		if(customerPhone==""){
			$("#customerPhone-label").html("<code>*请输入客户手机号*</code>");
			return false;
		}
		var pattern = /^[0-9]*$/;
		if(!pattern.test(customerPhone)){
			$("#customerPhone-label").html("<code>*手机号格式不正确,请输入正确的手机号*</code>");
			return false;
		}
		
		var data = {
			customerAccount:customerPhone,
			customerPhone:customerPhone,
			customerPassword:'whatever',//随便写
			customerName:customerName,
			customerGender:customerGender,
			customerCompany:customerCompany
		}
		if(isEmpty(customerId)){
			postJson("system/customer/saveCustomer",function (json, textStatus){
				if(json.success){
					bootbox.alert("客户添加成功");
					$('#customer-table').bootstrapTable("refresh",{silent: true});
				}else{
					bootbox.alert("客户添加失败:"+json.result);
				}
		    },data);
		}else{
			data['customerId'] = customerId;
			postJson("system/customer/editCustomer",function (json, textStatus){
				if(json.success){
					bootbox.alert("客户修改成功");
					$('#customer-table').bootstrapTable("refresh",{silent: true});
				}else{
					bootbox.alert("客户修改失败:"+json.result);
				}
		    },data);
		}
	});
	
	$('#pushMessageBtn').click(function(){
		var customerId = $('#pushMessageBtn').data("id");
		$('#customerId').val(customerId);
		$('#title').val('');
		$('#content').val('');
		$('#payload').val('-1');
		$("#pushMessage-modal").modal("show");
	});
	$('#pushMessage-send-btn').click(function(){
		var data = {};
		
		var customerId = $('#customerId').val();
		if(isEmpty(customerId)){
			bootbox.alert("客户ID不存在，请重新点击详情");
			$("#pushMessage-modal").modal("hide");
			return false;
		}
		data['customerId'] = customerId;
		
		var title = $('#title').val();
		if(isEmpty(title)){
			$("#title-label").html("<code>*请输入消息标题*</code>");
			return false;
		}
		data['title'] = title;
		
		var content = $('#content').val();
		if(isEmpty(content)){
			$("#content-label").html("<code>*请输入消息内容*</code>");
			return false;
		}
		data['content'] = content;
		
		var payload = $('#payload').val();
		if(payload != -1){
			data['payload'] = payload;
		}
		
		post("system/customer/pushMessage",function (data, textStatus) {
			if(data!=null && data.success==true){
				bootbox.alert("消息推送成功");
				$("#pushMessage-modal").modal("hide");
			}else{
				bootbox.alert("推送消息失败："+data.result);
			}
		},data);
	});
});

function nameFormatter(value, row, index){
	var icon = index % 2 === 0 ? 'glyphicon-star' : 'glyphicon-star-empty';
	return '<i class="glyphicon ' + icon + '"></i> ' + defindEmpty(value,'--');
}

function genderFormatter(value, row, index){
	if(value==1){
		return '先生';
	}else if(value==0){
		return '女士';
	}
}

function iconFormatter(value, row, index){
	if(value!=null && value!=""){
		return "<img src='"+value+"' width='50px' />";
	}else{
		return value;
	}
}

function lockedFormatter(value, row, index){
	if(value){
		return '<label style="color:red;">锁定</label>';
	}else{
		return '<label style="color:green;">未锁定</label>';
	}
}

function operateFormatter(value, row, index) { 
    return [
        '<a class="detail" href="javascript:void(0);" title="详情">',
            '<i class="glyphicon glyphicon-edit"></i>详情',
        '</a>&nbsp;&nbsp;',
        '<a class="edit" href="javascript:void(0);" title="编辑">',
	        '<i class="glyphicon glyphicon-edit"></i>编辑',
	    '</a>&nbsp;&nbsp;',
	    '<a class="resetPassword" href="javascript:void(0);" title="重置密码">',
	       	'<i class="glyphicon glyphicon-repeat"></i>重置密码',
	    '</a>&nbsp;&nbsp;',
	    '<a class="locked" href="javascript:void(0);" title="锁定/解锁">',
	       	'<i class="glyphicon glyphicon-lock"></i>'+(row.locked?'解锁':'锁定'),
	    '</a>&nbsp;&nbsp;',
        '<a class="remove" href="javascript:void(0);" title="删除">',
            '<i class="glyphicon glyphicon-remove"></i>删除',
        '</a>'
    ].join('');
}

window.operateEvents = {
	'click .detail': function (e, value, row, index) {
		post("system/customer/findCustomerById",function (json, textStatus) {
			if(json!=null && json.success==true && json.result!=null){
				var customer = json.result;
				
				$('#pushMessageBtn').data("id",customer.customerId);
				if(isEmpty(customer.clientId)){
					$('#pushMessageBtn').hide();
				}else{
					$('#pushMessageBtn').show();
				}
				
				$('#cname').text(defindEmpty(customer.customerName,'--'));
				$('#caccount').text(defindEmpty(customer.customerAccount,'--'));
				$('#cphone').text(defindEmpty(customer.customerPhone,'--'));
				$('#cgender').text(defindEmpty(customer.customerGender,'--'));
				if(isEmpty(customer.customerGender)){
					$('#cgender').text('--');
				}else if(customer.customerGender==1){
					$('#cgender').text('先生');
				}else if(customer.customerGender==0){
					$('#cgender').text('女士');
				}
				$('#ccompany').text(defindEmpty(customer.customerCompany,'--'));
				if(isEmpty(customer.customerPhoto)){
					$('#cphoto').text('--');
				}else{
					$('#cphoto').html('<img src="'+customer.customerPhoto+'" width="60px" />');
				}
				$('#dsystem').text(defindEmpty(customer.deviceSystem,'--'));
				$('#dvendor').text(defindEmpty(customer.deviceVendor,'--'));
				$('#dmodel').text(defindEmpty(customer.deviceModel,'--'));
				$('#duuid').text(defindEmpty(customer.deviceUuid,'--'));
				$('#ctoken').text(defindEmpty(customer.clientId,'--'));
				$('#cversion').text(defindEmpty(customer.clientVersion,'--'));
				$('#lastloginaddress').text(defindEmpty(customer.lastLoginAddress,'--'));
				$('#lastlogintime').text(defindEmpty(customer.lastLoginTime,'--'));
				$('#ccreatetime').text(defindEmpty(customer.createTime,'--'));
				$('#cmodifytime').text(defindEmpty(customer.modifyTime,'--'));
				$('#customerDetail').removeClass('hidden');
				
//				post("system/machine/findMachinesByCustomerId",function (data, textStatus) {
//					if(data!=null && data.success==true && data.result!=null && data.result.length>0){
//						$.each(data.result,function(i,v){
//							
//						});
//					}else{
//						$('#customerMachines').html('<div class="col-xs-12 col-sm-12 col-md-12">此用户没有设备</div>')
//					}
//				},{customerId:row.customerId});
			}else{
				bootbox.alert("获取用户信息失败");
			}
		},{customerId:row.customerId});
	},
	'click .edit': function (e, value, row, index) {
		post("system/customer/findCustomerById",function (json, textStatus) {
			if(json!=null && json.success==true && json.result!=null){
				var customer = json.result;
				$('#customerId').val(customer.customerId);
				$("#customerPhone").val(customer.customerPhone);
				$("#customerPhone").prop('readonly','readonly');
				$("#customerName").val(customer.customerName);
				if(customer.customerGender==1){
					$("#customerMale").prop('checked','checked');
				}else if(customer.customerGender==0){
					$("#customerFemale").prop('checked','checked');
				}
				$("#customerCompany").val(customer.customerCompany);
				$(".info-label").html("");
				$("#customerinfo-modal").modal("show");
			}else{
				bootbox.alert("获取用户信息失败");
			}
		},{customerId:row.customerId});
	},
	'click .resetPassword': function (e, value, row, index) {
		bootbox.confirm("您确定要恢复初始密码吗？", function(result){
			if(result){
				post("system/customer/resetCustomerPassword",function (json, textStatus) {
					if(json.success){
						bootbox.alert("密码重置成功");
					}else{
						bootbox.alert("密码重置失败");
					}
				},{ids:row.customerId});
			}
		});
	},
	'click .locked': function (e, value, row, index) {
		var txt = row.locked?'解锁':'锁定';
		bootbox.confirm("您确定要"+txt+"用户账号吗？", function(result){
			if(result){
				post("system/customer/lockedCustomer",function (json, textStatus) {
					if(json.success){
						bootbox.alert(txt+"用户账号成功");
						$('#customer-table').bootstrapTable("refresh",{silent: true});
					}else{
						bootbox.alert(txt+"用户账号失败");
					}
				},{ids:row.customerId});
			}
		});
	},
	'click .remove': function (e, value, row, index) {
		bootbox.confirm("您确定要将客户删除吗？", function(result){
			if(result){
				del("system/customer/delCustomers/"+row.customerId,function (json, textStatus) {
					if(json.success){
						bootbox.alert("客户删除成功");
						$('#customer-table').bootstrapTable("refresh",{silent: true});
					}else{
						bootbox.alert("客户删除失败");
					}
				});
			}
		});
	}
};